package repository

import (
	"context"
	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/db"
	dbmodel "gitee.com/hp-huiw/family-expense-api/internal/db/model"
	jet "github.com/go-jet/jet/v2/mysql"
)

type RequestMapRepository interface {
	Exists(ctx context.Context) (bool, error)
	Query(ctx context.Context) ([]dbmodel.RequestMap, error)
	BatchInsert(ctx context.Context, models []dbmodel.RequestMap) error
}

func NewRequestMapRepository(db *sql.DB) RequestMapRepository {
	return &requestMapRepository{db: db}
}

func (r *requestMapRepository) Exists(ctx context.Context) (bool, error) {
	return db.Exists(ctx, r.db, tbRequestMap, nil)
}

func (r *requestMapRepository) Query(ctx context.Context) ([]dbmodel.RequestMap, error) {
	var query []dbmodel.RequestMap

	stmt := jet.
		SELECT(tbRequestMap.AllColumns).
		FROM(tbRequestMap)

	err := stmt.QueryContext(ctx, r.db, &query)

	if err != nil {
		return nil, err
	}

	return query, nil
}

func (r *requestMapRepository) BatchInsert(ctx context.Context, models []dbmodel.RequestMap) error {
	stmt := tbRequestMap.
		INSERT().
		MODELS(models)

	_, err := stmt.ExecContext(ctx, r.db)

	return err
}

type requestMapRepository struct {
	db *sql.DB
}
